#include "server.h"

int usrinfoInit(usrinfo_t* usrinfo){
    bzero(usrinfo,sizeof(usrinfo_t));
    return 0;
}

int usrinfoInsert(usrinfo_t* usrinfo,char* usr_name,int netfd){
    usrnode_t* new_node = (usrnode_t *)calloc(1,sizeof(usrnode_t));
    new_node->netfd = netfd;
    memcpy(new_node->usr_name,usr_name,strlen(usr_name));
    new_node->dirStack = stackDirInit();
    if(usrinfo->head == NULL){
        usrinfo->head = new_node;
    }else{
        new_node->pnext = usrinfo->head;
        usrinfo->head = new_node;
    }
    return 0;
}

int usrinfodel(usrinfo_t* usrinfo,int netfd){
    usrnode_t* cur = usrinfo->head;
    if(usrinfo->head->netfd == netfd){
        usrinfo->head = usrinfo->head->pnext;
        free(cur);
        return 0;
    }
    usrnode_t* tmp;
    while(cur->pnext->netfd == netfd){
        cur = cur->pnext;
    }
    tmp = cur->pnext;
    cur->pnext = cur->pnext->pnext;
    free(tmp);
    return 0;
}

int delusrinfo(usrinfo_t* usrinfo){
    usrnode_t* tmp;
    while(usrinfo->head){
        tmp = usrinfo->head;
        usrinfo->head = usrinfo->head->pnext;
        free(tmp);
    }
    free(usrinfo);
    return 0;
}

int netfd_to_usrname(usrinfo_t* usrinfo,int netfd,char* usrname){
    usrnode_t* cur = usrinfo->head;
    while(cur->netfd != netfd){
        cur = cur->pnext;
    }
    memcpy(usrname,cur->usr_name,strlen(cur->usr_name) + 1);
    return 0;
}

int inserttoken(usrinfo_t* usrinfo,int netfd,char* token){
    usrnode_t* cur = usrinfo->head;
    while(cur->netfd != netfd){
        cur = cur->pnext;
    }
    memcpy(cur->token,token,strlen(token));
    return 0;
}

stackDir_t* netfd_to_dirStack(usrinfo_t* usrinfo,int netfd){
    usrnode_t* cur = usrinfo->head;
    while(cur->netfd != netfd){
        cur = cur->pnext;
    }
    return cur->dirStack;
}

stackDir_t* usrname_to_dirStack(usrinfo_t* usrinfo,char* usrname){
    usrnode_t* cur = usrinfo->head;
    while(strcmp(cur->usr_name,usrname)){
        cur = cur->pnext;
    }
    return cur->dirStack;
}
